package com.woniuxy.order.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.alibaba.nacos.shaded.io.grpc.netty.shaded.io.netty.util.internal.StringUtil;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniuxy.core.config.AlipayConfiguration;
import com.woniuxy.core.exception.accountException.AccountException;
import com.woniuxy.core.exception.accountException.AccountExceptionCode;
import com.woniuxy.core.exception.certifiedException.CertifiedException;
import com.woniuxy.core.exception.certifiedException.CertifiedExceptionCode;
import com.woniuxy.core.exception.orderException.OrderException;
import com.woniuxy.core.exception.orderException.OrderExceptionCode;
import com.woniuxy.core.exception.stallException.StallException;
import com.woniuxy.core.exception.stallException.StallExceptionCode;
import com.woniuxy.core.model.GetOrdersByStallIdAndTimeForm;
import com.woniuxy.core.model.PageInfo;
import com.woniuxy.core.model.Result;
import com.woniuxy.core.staticCode.OrderCode;
import com.woniuxy.core.staticCode.StallInfoCode;
import com.woniuxy.core.staticCode.StallTypeCode;
import com.woniuxy.core.util.AlipayUtil;
import com.woniuxy.core.util.DateUtil;
import com.woniuxy.order.model.dto.CertifiedInfo;
import com.woniuxy.order.dao.OrderInfo;
import com.woniuxy.order.dao.OrderOvertime;
import com.woniuxy.order.feign.CertifiedClient;
import com.woniuxy.order.feign.RentersClient;
import com.woniuxy.order.feign.StallInfoClient;
import com.woniuxy.order.feign.UserInfoClient;
import com.woniuxy.order.mapper.OrderInfoMapper;
import com.woniuxy.order.service.OrderInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.order.service.OrderOvertimeService;
import com.woniuxy.order.service.impl.dto.RenterOrderDTO;
import com.woniuxy.order.service.param.*;

import com.woniuxy.order.service.RenterWaitingToUseOrder;
import com.woniuxy.core.param.PagePayParam;
import com.woniuxy.order.service.impl.dto.OrderInfoDTO;
import com.woniuxy.renters.dao.RentersInfo;
import com.woniuxy.stall.dao.StallInfo;
import com.woniuxy.stall.dao.StallRentTime;
import com.woniuxy.user.dao.UserInfo;
import lombok.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.*;
import java.util.function.Consumer;


/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 凌玉春
 * @since 2024年01月15日
 */
@Service
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements OrderInfoService {
    @Autowired
    private CertifiedClient certifiedClient;
    @Autowired
    private StallInfoClient stallInfoClient;
    @Autowired
    private UserInfoClient userInfoClient;
    @Autowired
    private OrderInfoMapper orderInfoMapper;
    @Autowired
    private AlipayUtil alipayUtil;
    @Resource
    private AlipayConfiguration alipayConfiguration;
    @Autowired
    private OrderOvertimeService orderOvertimeService;
    @Autowired
    private RentersClient rentersClient;

    DecimalFormat df = new DecimalFormat("#.00");

    //成员内部类
    @AllArgsConstructor
    @NoArgsConstructor
    @Getter
    public enum myEnum{
        GENERAL_ADMIN(1,"普通管理员"),SUPER_ADMIN(0,"超级管理员"),
        ;
        @Setter private Integer code;
        @Setter private String message;

    }




    @Override
    public void creatOrder(CreatOrderParam param) {

        Result<Boolean> booleanResult = userInfoClient.loadAllUserinfosss(String.valueOf(param.getUserInfoId()));
        Boolean data = booleanResult.getData();
        System.out.println("---------------------");
        System.out.println(data);
        System.out.println("---------------------");
        System.out.println("123123123");
        if (!data){
            throw new AccountException(AccountExceptionCode.ID_NOT);
        }

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime startTime = LocalDateTime.parse(param.getStartTime(), formatter);
        LocalDateTime endTime = LocalDateTime.parse(param.getEndTime(), formatter);
        Duration duration = Duration.between(startTime, endTime);
        long minutes = duration.toMinutes();
        if (minutes<=0) throw new OrderException(OrderExceptionCode.ORDER_TIME_ERRO);
        Result<StallInfo> stallInfoResult = stallInfoClient.findStallById(param.getStatllInfoId());
        if (stallInfoResult.getData()==null) throw new StallException(StallExceptionCode.STALL_NOT_EXIST);
        StallInfo stallInfo = stallInfoResult.getData();
        param.setCentifiedInfoId(stallInfo.getCertifiedInfoId());
        Result<CertifiedInfo> result = certifiedClient.findCertifiedInfoById(param.getCentifiedInfoId());
        if (result.getCode()!=200) throw new CertifiedException(CertifiedExceptionCode.CERTIFIED_NOT_EXIST);
        Integer stallInfoId = stallInfo.getStallInfoId();
        Result<StallRentTime> rentTimeResult=stallInfoClient.getStallRentTimeByStallId(stallInfoId);
        StallRentTime stallRentTime = rentTimeResult.getData();
        String rentStartTime1 = stallRentTime.getRentStartTime();
        String rentEndTime1 = stallRentTime.getRentEndTime();
        String nowString = LocalDate.now().toString();
        String rentStartTimes=nowString+" "+rentStartTime1;
        String rentEndTimes=nowString+" "+rentEndTime1;
        LocalTime rentStartTime = DateUtil.StringToLocalTime(rentStartTimes);
        LocalTime rentEndTime = DateUtil.StringToLocalTime(rentEndTimes);
        if (rentStartTime.isAfter(LocalTime.from(startTime))||rentEndTime.isBefore(LocalTime.from(endTime))){
            throw new StallException(StallExceptionCode.STALL_CANT_USE);
        }
        QueryWrapper<OrderInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("statll_info_id",param.getStatllInfoId())
                .and(w->w.between("start_time",param.getStartTime(),param.getEndTime()).or().between("end_time",param.getStartTime(),param.getEndTime())
                        .or().ge("end_time",param.getEndTime()).le("start_time",param.getStartTime()));
        Long count = orderInfoMapper.selectCount(wrapper);
        if (count!=0) throw new StallException(StallExceptionCode.STALL_CANT_USE);
        StallTypeCode[] values = StallTypeCode.values();
        String typeName=null;
        for (StallTypeCode value : values) {
            if (value.getCode()==stallInfoResult.getData().getStallTpye()){
                typeName= value.getMessage();
            }
        }
        param.setStallType(typeName);
        long hours=minutes%60==0?minutes/60:minutes/60+1;
        OrderInfo orderInfo = BeanUtil.toBean(param, OrderInfo.class);
        orderInfo.setStartTime(startTime);
        orderInfo.setEndTime(endTime);
        orderInfo.setEndoHour((int)hours);
        BigDecimal hourPrice=stallInfoResult.getData().getStallTpye()==1?result.getData().getChargeUnitPrice():result.getData().getStallUnitPrice();
        orderInfo.setOrderPrice(hourPrice.multiply(new BigDecimal(orderInfo.getEndoHour())));
        orderInfo.setOrderInfoState(OrderCode.ORDER_NOT_PAY.getCode());
        orderInfo.setOrderAddTime(LocalDateTime.now());
        Snowflake snowflake = new Snowflake(1);
        orderInfo.setOrderInfoNum(snowflake.nextIdStr());
        orderInfo.setIsComment(OrderCode.ORDER_NO_COMMENT.getCode());
        orderInfoMapper.insert(orderInfo);
    }

    @Override
    public List<RenterWaitingToUseOrder> findRenterWaitingToUseOrder(Integer renterId) {
        LocalDateTime now = LocalDateTime.now();
        QueryWrapper<OrderInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("user_info_id",renterId);
        wrapper.gt("start_time",now);
        List<OrderInfo> orderInfos = orderInfoMapper.selectList(wrapper);
        if (orderInfos.size()==0) throw new OrderException(OrderExceptionCode.NO_WAITING_ORDER);
        List<RenterWaitingToUseOrder> list=new ArrayList<>();
        for (OrderInfo orderInfo : orderInfos) {
            RenterWaitingToUseOrder waitingToUseOrder = BeanUtil.toBean(orderInfo, RenterWaitingToUseOrder.class);
            Result<CertifiedInfo> certifiedInfo = certifiedClient.findCertifiedInfoById(orderInfo.getCentifiedInfoId());
            waitingToUseOrder.setCentifiedName(certifiedInfo.getData().getCertifiedInfoName());
            if (orderInfo.getOrderInfoState()==OrderCode.ORDER_NOT_PAY.getCode()){
                waitingToUseOrder.setOrderInfoState(OrderCode.ORDER_NOT_PAY.getMessage());
            }else {
                waitingToUseOrder.setOrderInfoState("待进行");
            }
            Result<String> result = stallInfoClient.findStallNumById(orderInfo.getStatllInfoId());
            waitingToUseOrder.setStallInfoNum(result.getData());
            list.add(waitingToUseOrder);
        }
        return list;
    }

    @Override
    public void delWaitToUseOrder(Integer renterId, String orderInfoNum) {
        QueryWrapper<OrderInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("user_info_id",renterId);
        wrapper.eq("order_info_num",orderInfoNum);
        wrapper.gt("start_time",LocalDateTime.now());
        OrderInfo orderInfo = orderInfoMapper.selectOne(wrapper);

        if (orderInfo==null){
            throw new OrderException(OrderExceptionCode.NO_ORDER_CAN_DEL);
        }
        orderInfoMapper.deleteById(orderInfo.getOrderInfoId());
    }

    @Override
    public String pagePayEarnest(String orderNum) throws Exception {
        QueryWrapper<OrderInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("order_info_num", orderNum);
        OrderInfo orderInfo = orderInfoMapper.selectOne(wrapper);
        if ((orderInfo==null)){
            throw new OrderException(OrderExceptionCode.ORDER_INEXISTENCE);
        }
        if (orderInfo.getOrderInfoState()!=OrderCode.ORDER_NOT_PAY.getCode()){
            throw new OrderException(OrderExceptionCode.ORDER_HAS_PAY_Earnest);
        }
        PagePayParam param = new PagePayParam();
        param.setOrderNum(orderNum);
        param.setBody("支付定金");
        param.setSubject("支付定金");
        param.setMoney(orderInfo.getOrderPrice().doubleValue()/2);
        param.setReturnUrl("http://www.baidu.com");
        param.setNotifyUrl("http://wbj3qs.natappfree.cc/order/orderInfo/pagePayEarnestNotify");
        String html = alipayUtil.pagePay(param);
        return html;
    }

    @Override
    public void pagePayEarnestNotify(Map<String, String> param) throws AlipayApiException {
        boolean signVerified = AlipaySignature.rsaCheckV1(param, alipayConfiguration.getAlipayPublicKey(),"utf-8", "RSA2"); //调用SDK验证签名
        if(signVerified) {
            //验签通过
            //取出订单编号
            String orderNum = param.get("out_trade_no");
            String tradeStatus = param.get("trade_status");
            String payTime = param.get("gmt_payment");
            if("TRADE_SUCCESS".equals(tradeStatus)) {
                System.out.println("定金支付成功了！！！！！！！！！！！！！！！！！");
                QueryWrapper<OrderInfo> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("order_info_num",orderNum);
                OrderInfo orderInfo = orderInfoMapper.selectOne(queryWrapper);
                if(orderInfo!=null&&OrderCode.ORDER_NOT_PAY.getCode()==orderInfo.getOrderInfoState()) {
                    //更新订单状态
                    UpdateWrapper<OrderInfo> wrapper = new UpdateWrapper<>();
                    wrapper.set("order_info_state",OrderCode.ORDER_HAS_PAY_Earnest.getCode());
                    wrapper.eq("order_info_num",orderNum);
                    orderInfoMapper.update(null,wrapper);
                    Snowflake snowflake = new Snowflake(1);
                    String newNum=snowflake.nextIdStr();
                    UpdateWrapper<OrderInfo> orderInfoUpdateWrapper = new UpdateWrapper<>();
                    orderInfoUpdateWrapper.eq("order_info_num",orderNum);
                    orderInfoUpdateWrapper.set("order_info_num",newNum);
                    orderInfoMapper.update(null,orderInfoUpdateWrapper);
                }
            }
        } else {//验证失败

        }
    }

    @Override
    public String pagePay(String orderNum) throws Exception {
        QueryWrapper<OrderInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("order_info_num",orderNum);
        OrderInfo orderInfo = orderInfoMapper.selectOne(wrapper);
        if (orderInfo==null){
            throw new OrderException(OrderExceptionCode.ORDER_INEXISTENCE);
        }
        Integer orderInfoState = orderInfo.getOrderInfoState();
        if (orderInfoState==OrderCode.ORDER_PAYED.getCode()||orderInfoState==OrderCode.ORDER_OVER_TIME_PAYED.getCode()){
            throw new OrderException(OrderExceptionCode.ORDER_DOUBLEPAYMENT);
        }
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime orderInfoStartTime = orderInfo.getStartTime();
        Duration duration = Duration.between(orderInfoStartTime, now);
        long minutes = duration.toMinutes();
        long hours=minutes%60==0?minutes/60:minutes/60+1;
        Result<StallInfo> stallInfo = stallInfoClient.findStallById(orderInfo.getStatllInfoId());
        if (stallInfo.getData()==null) throw new StallException(StallExceptionCode.STALL_NOT_EXIST);
        Result<CertifiedInfo> result = certifiedClient.findCertifiedInfoById(orderInfo.getCentifiedInfoId());
        BigDecimal hourPrice=stallInfo.getData().getStallTpye()==1?result.getData().getChargeUnitPrice():result.getData().getStallUnitPrice();
        BigDecimal realPrice=hourPrice.multiply(new BigDecimal(hours)).subtract(new BigDecimal(orderInfo.getOrderPrice().doubleValue()/2));
        if (now.compareTo(orderInfo.getEndTime())<=0){
            //没超时
            //支付尾款
            PagePayParam param = new PagePayParam();
            param.setOrderNum(orderNum);
            param.setBody("支付尾款");
            int i = realPrice.compareTo(BigDecimal.ZERO);
            if (i<=0){
                orderInfo.setOrderPrice(new BigDecimal(orderInfo.getOrderPrice().doubleValue()/2));
                orderInfo.setOrderInfoState(OrderCode.ORDER_PAYED.getCode());
                orderInfo.setIsComment(OrderCode.ORDER_NO_COMMENT.getCode());
                orderInfo.setEndTime(now);
                orderInfo.setEndoHour((int) hours);
                orderInfoMapper.updateById(orderInfo);
                throw new OrderException(OrderExceptionCode.ORDER_NOT_NEED_PAY);
            }
            param.setMoney(realPrice.doubleValue());
            param.setReturnUrl("http://www.baidu.com");
            param.setNotifyUrl("http://wbj3qs.natappfree.cc/order/orderInfo/pagePayNotify");
            String html = alipayUtil.pagePay(param);
            return html;
        }else {
            //超时了,新增超时订单
            orderInfo.setIsOvertime(OrderCode.ORDER_OVER_TIME.getCode());
            orderInfoMapper.updateById(orderInfo);
            OrderOvertime orderOvertime = BeanUtil.toBean(orderInfo, OrderOvertime.class);
            orderOvertime.setEndTime(now);
            orderOvertime.setOrderSeatId(orderInfo.getStatllInfoId());
            orderOvertime.setPayPrice(realPrice);
            orderOvertime.setEndoHour((int) hours);
            orderOvertime.setPayState(OrderCode.ORDER_OVER_TIME_NOT_PAY.getCode());
            orderOvertimeService.add(orderOvertime);
            //支付超时订单
            PagePayParam param = new PagePayParam();
            param.setOrderNum(orderNum);
            param.setBody("支付超时订单尾款");
            param.setMoney(orderOvertime.getPayPrice().doubleValue());
            param.setReturnUrl("http://www.baidu.com");
            param.setNotifyUrl("http://wbj3qs.natappfree.cc/order/orderInfo/pagePayNotify");
            String html = alipayUtil.pagePay(param);
            return html;
        }
    }

    @Override
    public void pagePayNotify(Map<String, String> param) throws AlipayApiException {
        boolean signVerified = AlipaySignature.rsaCheckV1(param, alipayConfiguration.getAlipayPublicKey(),"utf-8", "RSA2"); //调用SDK验证签名
        if(signVerified) {
            //验签通过
            //取出订单编号
            String orderId = param.get("out_trade_no");
            String tradeStatus = param.get("trade_status");
            String payTime = param.get("gmt_payment");
            BigDecimal amount = new BigDecimal(param.get("invoice_amount"));
            if("TRADE_SUCCESS".equals(tradeStatus)) {
                System.out.println("尾款支付成功！！！！！！！！！！！！！！");
                OrderOvertime orderOvertime = orderOvertimeService.getOne(new QueryWrapper<OrderOvertime>().eq("order_info_num", orderId));
                if(orderOvertime!=null&&OrderCode.ORDER_OVER_TIME_NOT_PAY.getCode()==orderOvertime.getPayState()) {
                    //更新超时订单状态
                    UpdateWrapper<OrderOvertime> wrapper = new UpdateWrapper<>();
                    wrapper.set("pay_state",OrderCode.ORDER_OVER_TIME_PAYED.getCode());
                    orderOvertimeService.update(wrapper);
                    UpdateWrapper<OrderInfo> orderInfoUpdateWrapper = new UpdateWrapper<>();
                    orderInfoUpdateWrapper.set("order_info_state",OrderCode.ORDER_OVER_TIME_PAYED.getCode());
                    orderInfoUpdateWrapper.eq("order_info_num",orderId);
                    orderInfoMapper.update(null,orderInfoUpdateWrapper);
                }
                if (ObjectUtil.isEmpty(orderOvertime)){
                    //不是超时订单
                    QueryWrapper<OrderInfo> wrapper = new QueryWrapper<>();
                    wrapper.eq("order_info_num",orderId);
                    OrderInfo orderInfo = orderInfoMapper.selectOne(wrapper);
                    orderInfo.setOrderPrice(amount.add(new BigDecimal(orderInfo.getOrderPrice().doubleValue()/2)));
                    orderInfo.setOrderInfoState(OrderCode.ORDER_PAYED.getCode());
                    orderInfoMapper.updateById(orderInfo);
                }
            }
        } else {//验证失败

        }
    }

    @Override
    public PageInfo platformGetOrderPage(PlatformGetOrderParam param) throws ParseException {
        Integer centifiedInfoId = param.getCentifiedInfoId();
        Integer stallTypeId = param.getStallTypeId();
        System.out.println(stallTypeId);
        if (!ObjectUtil.isEmpty(stallTypeId)){
            if (stallTypeId!=1&&stallTypeId!=2&&stallTypeId!=0){
                throw new StallException(StallExceptionCode.STALL_NOT_EXIST);
            }
        }

        Integer timeSortId = param.getTimeSortId();
        if (!ObjectUtil.isEmpty(timeSortId)){
            if (timeSortId!=0&&timeSortId!=1&&timeSortId!=2){
                throw new OrderException(OrderExceptionCode.Order_sort_erro);
            }
        }

        QueryWrapper<OrderInfo> wrapper = new QueryWrapper<>();
        if (centifiedInfoId!=0&&null!=centifiedInfoId){
            wrapper.eq("centified_info_id",centifiedInfoId);
        }
        if (!ObjectUtil.isEmpty(stallTypeId)){
            if (stallTypeId!=0){
                String stallType=stallTypeId==1?"普通车位":"充电车位";
                wrapper.eq("stall_type",stallType);
            }
        }
        if (timeSortId!=0&&null!=timeSortId){
            if (timeSortId==1){
                wrapper.orderByDesc("order_add_time");
            }else {
                wrapper.orderByAsc("order_add_time");
            }

        }
        String paramStartTime = param.getStartTime();
        String paramEndTime = param.getEndTime();
        if (!ObjectUtil.isEmpty(paramEndTime)&&!ObjectUtil.isEmpty(paramStartTime)){
            boolean b = DateUtil.compareDataAndString(paramStartTime, paramEndTime);
            if (b){
                throw new OrderException(OrderExceptionCode.ORDER_TIME_SORT_ERRO);
            }
            wrapper.gt("start_time",paramStartTime);
            String tomorrowStringDate = DateUtil.getTomorrowStringDate(paramEndTime);
            wrapper.lt("end_time",tomorrowStringDate);
        }
        if (null==paramStartTime&&null!=paramEndTime){
            String tomorrowStringDate = DateUtil.getTomorrowStringDate(paramEndTime);
            wrapper.lt("end_time",tomorrowStringDate);
        }
        if (null!=paramStartTime&&null==paramEndTime){
            wrapper.gt("start_time",paramStartTime);
        }
        Page<OrderInfo> page = new Page<>(param.getCurrent() == null ? 1 : param.getCurrent(), param.getSize() == null ? 3 : param.getSize());
        Page<OrderInfo> orderInfoPage = orderInfoMapper.selectPage(page, wrapper);
        ArrayList<OrderInfoDTO> dto=new ArrayList<OrderInfoDTO>();
        List<OrderInfo> records = orderInfoPage.getRecords();
        for (OrderInfo orderInfo : records) {
            OrderInfoDTO orderInfoDTO = BeanUtil.toBean(orderInfo, OrderInfoDTO.class);
            Result<UserInfo> userInfoResult = userInfoClient.loadAllUserinfobyId(orderInfo.getUserInfoId());
            String userInfoName = userInfoResult.getData().getUserInfoName();
            orderInfoDTO.setUserInfoName(userInfoName);
            Result<CertifiedInfo> certifiedInfoResult = certifiedClient.findCertifiedInfoById(orderInfoDTO.getCentifiedInfoId());
            String certifiedInfoName = certifiedInfoResult.getData().getCertifiedInfoName();
            orderInfoDTO.setCertifiedInfoName(certifiedInfoName);
            Result<String> stallNum = stallInfoClient.findStallNumById(orderInfoDTO.getStatllInfoId());
            orderInfoDTO.setStallInfoNum(stallNum.getData());
            dto.add(orderInfoDTO);
        }
        PageInfo pageInfo = BeanUtil.toBean(page, PageInfo.class);
        pageInfo.setPages(page.getPages());
        pageInfo.setRecords(dto);
        return pageInfo;
    }

    @Override
    public PageInfo platformGetOverTimeOrderPage(PlatformGetOverTimeOrderParam param) {
        Page<OrderOvertime> page = new Page<>(param.getCurrent() == null ? 1 : param.getCurrent(), param.getSize() == null ? 3 : param.getSize());
        return orderOvertimeService.platformGetOverTimeOrderPage(page);
    }

    @Override
    public PageInfo getRenterOrders(RenterOrderParam param) {
        Integer renterId = param.getRenterId();
        Result<RentersInfo> result = rentersClient.loadAllRentersinfobyId(renterId);
        RentersInfo renterInfo = result.getData();
        String stallInfoIdString = renterInfo.getStallInfoId();
        JSONArray jsonArray = JSONUtil.parseArray(stallInfoIdString);
        List<Integer> ids = JSONUtil.toList(jsonArray, Integer.class);
        ArrayList<StallInfo> stallInfos=new ArrayList<>();
        for (Integer id : ids) {
            Result<StallInfo> result1 = stallInfoClient.findStallById(id);
            stallInfos.add(result1.getData());

        }
        QueryWrapper<OrderInfo> wrapper = new QueryWrapper<>();
        wrapper.in("statll_info_id",ids);
        Page<OrderInfo> page = new Page<>(param.getCurrent() == null ? 1 : param.getCurrent(), param.getSize() == null ? 3 : param.getSize());
        Page<OrderInfo> orderInfoPage = orderInfoMapper.selectPage(page, wrapper);
        List<OrderInfo> orderInfos = orderInfoPage.getRecords();
        List<RenterOrderDTO> dto=new ArrayList<>();
        for (OrderInfo orderInfo : orderInfos) {
            RenterOrderDTO renterOrderDTO = BeanUtil.toBean(orderInfo, RenterOrderDTO.class);
            for (StallInfo stallInfo : stallInfos) {
                if (stallInfo.getStallInfoId()==orderInfo.getStatllInfoId()){
                    renterOrderDTO.setStallInfoNum(stallInfo.getStallInfoNum());
                }
            }
            if (orderInfo.getIsOvertime()==OrderCode.ORDER_OVER_TIME.getCode()){
                QueryWrapper<OrderOvertime> orderOvertimeQueryWrapper = new QueryWrapper<>();
                orderOvertimeQueryWrapper.eq("order_info_num",orderInfo.getOrderInfoNum());
                OrderOvertime one = orderOvertimeService.getOne(orderOvertimeQueryWrapper);
                Integer endoHour = one.getEndoHour();
                renterOrderDTO.setEndoHour(endoHour);
            }
            dto.add(renterOrderDTO);
        }
        PageInfo pageInfo = BeanUtil.toBean(page, PageInfo.class);
        pageInfo.setPages(page.getPages());
        pageInfo.setRecords(dto);
        return pageInfo;
    }

    @Override
    public PageInfo getCerOrders(Integer id, Integer current, Integer size) {

        Page<OrderInfo> page = new Page<>(current == null ? 1 : current, size == null ? 3 : size);
        QueryWrapper<OrderInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("centified_info_id",id);
        Page<OrderInfo> orderInfoPage = orderInfoMapper.selectPage(page, wrapper);
        ArrayList<OrderInfoDTO> dto=new ArrayList<OrderInfoDTO>();
        List<OrderInfo> records = orderInfoPage.getRecords();
        for (OrderInfo orderInfo : records) {
            OrderInfoDTO orderInfoDTO = BeanUtil.toBean(orderInfo, OrderInfoDTO.class);
            Result<UserInfo> userInfoResult = userInfoClient.loadAllUserinfobyId(orderInfo.getUserInfoId());
            String userInfoName = userInfoResult.getData().getUserInfoName();
            orderInfoDTO.setUserInfoName(userInfoName);
            Result<CertifiedInfo> certifiedInfoResult = certifiedClient.findCertifiedInfoById(orderInfoDTO.getCentifiedInfoId());
            String certifiedInfoName = certifiedInfoResult.getData().getCertifiedInfoName();
            orderInfoDTO.setCertifiedInfoName(certifiedInfoName);
            Result<String> stallNum = stallInfoClient.findStallNumById(orderInfoDTO.getStatllInfoId());
            orderInfoDTO.setStallInfoNum(stallNum.getData());
            Integer state = orderInfo.getOrderInfoState();
            String stateName=null;
            OrderCode[] values = OrderCode.values();
            for (OrderCode orderCode : values) {
                if (state==orderCode.getCode()){
                    stateName=orderCode.getMessage();
                }
            }
            orderInfoDTO.setStateName(stateName);
            if (orderInfo.getIsOvertime()==OrderCode.ORDER_OVER_TIME.getCode()){
                QueryWrapper<OrderOvertime> wrapper1 = new QueryWrapper<>();
                wrapper1.eq("order_info_id",orderInfo.getOrderInfoId());
                OrderOvertime one = orderOvertimeService.getOne(wrapper1);
                orderInfoDTO.setEndTime(one.getEndTime());
                orderInfoDTO.setEndoHour(one.getEndoHour());
                orderInfoDTO.setOrderPrice(one.getPayPrice());
                Integer payState = one.getPayState();
                for (OrderCode orderCode : values) {
                    if (payState==orderCode.getCode()){
                        stateName=orderCode.getMessage();
                        orderInfoDTO.setStateName(stateName);
                    }
                }
            }
            dto.add(orderInfoDTO);
        }
        PageInfo pageInfo = BeanUtil.toBean(page, PageInfo.class);
        pageInfo.setPages(page.getPages());
        pageInfo.setRecords(dto);
        return pageInfo;
    }

    @Override
    public List<OrderInfoDTO> selectOrderByCarPlate(String plate) {
        QueryWrapper<OrderInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("user_car_plate",plate);
        wrapper.orderByDesc("order_info_id");
        List<OrderInfo> list = orderInfoMapper.selectList(wrapper);
        //是否存在该车牌号的订单
        if(list.size()==0){
            throw new OrderException(OrderExceptionCode.ORDER_INEXISTENCE);
        }
        List<OrderInfoDTO> dto=new ArrayList<>();
        for (OrderInfo orderInfo : list) {
            OrderInfoDTO orderInfoDTO = BeanUtil.toBean(orderInfo, OrderInfoDTO.class);
            Result<UserInfo> userInfoResult = userInfoClient.loadAllUserinfobyId(orderInfo.getUserInfoId());
            String userInfoName = userInfoResult.getData().getUserInfoName();
            orderInfoDTO.setUserInfoName(userInfoName);
            Result<CertifiedInfo> certifiedInfoResult = certifiedClient.findCertifiedInfoById(orderInfoDTO.getCentifiedInfoId());
            String certifiedInfoName = certifiedInfoResult.getData().getCertifiedInfoName();
            orderInfoDTO.setCertifiedInfoName(certifiedInfoName);
            Result<String> stallNum = stallInfoClient.findStallNumById(orderInfoDTO.getStatllInfoId());
            orderInfoDTO.setStallInfoNum(stallNum.getData());
            Integer state = orderInfo.getOrderInfoState();
            String stateName=null;
            OrderCode[] values = OrderCode.values();
            for (OrderCode orderCode : values) {
                if (state==orderCode.getCode()){
                    stateName=orderCode.getMessage();
                }
            }
            orderInfoDTO.setStateName(stateName);
            if (orderInfo.getIsOvertime()==OrderCode.ORDER_OVER_TIME.getCode()){
                QueryWrapper<OrderOvertime> wrapper1 = new QueryWrapper<>();
                wrapper1.eq("order_info_id",orderInfo.getOrderInfoId());
                OrderOvertime one = orderOvertimeService.getOne(wrapper1);
                orderInfoDTO.setEndTime(one.getEndTime());
                orderInfoDTO.setEndoHour(one.getEndoHour());
                orderInfoDTO.setOrderPrice(one.getPayPrice());
                Integer payState = one.getPayState();
                for (OrderCode orderCode : values) {
                    if (payState==orderCode.getCode()){
                        stateName=orderCode.getMessage();
                        orderInfoDTO.setStateName(stateName);
                    }
                }
            }
            dto.add(orderInfoDTO);
        }
        return dto;
    }

    @Override
    public PageInfo getUserOrders(Integer id, Integer current, Integer size) {

        ArrayList<OrderInfoDTO> dto=new ArrayList<OrderInfoDTO>();
        Result<UserInfo> userInfoResult = userInfoClient.loadAllUserinfobyId(id);
        UserInfo userInfo = userInfoResult.getData();
        QueryWrapper<OrderInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("user_info_id",id);
        Page<OrderInfo> page = new Page<>(current == null ? 1 : current, size == null ? 3 : size);
        Page<OrderInfo> orderInfoPage = orderInfoMapper.selectPage(page, wrapper);
        List<OrderInfo> records = orderInfoPage.getRecords();
        for (OrderInfo orderInfo : records) {
            OrderInfoDTO orderInfoDTO = BeanUtil.toBean(orderInfo, OrderInfoDTO.class);
            orderInfoDTO.setUserInfoName(userInfo.getUserInfoName());
            Integer centifiedInfoId = orderInfo.getCentifiedInfoId();
            Result<CertifiedInfo> certifiedInfoResult = certifiedClient.findCertifiedInfoById(centifiedInfoId);
            CertifiedInfo certifiedInfo = certifiedInfoResult.getData();
            orderInfoDTO.setCertifiedInfoName(certifiedInfo.getCertifiedInfoName());
            Result<String> stallNum = stallInfoClient.findStallNumById(orderInfoDTO.getStatllInfoId());
            orderInfoDTO.setStallInfoNum(stallNum.getData());
            Integer state = orderInfo.getOrderInfoState();
            String stateName=null;
            OrderCode[] values = OrderCode.values();
            for (OrderCode orderCode : values) {
                if (state==orderCode.getCode()){
                    stateName=orderCode.getMessage();
                }
            }
            orderInfoDTO.setStateName(stateName);
            if (orderInfo.getIsOvertime()==OrderCode.ORDER_OVER_TIME.getCode()){
                QueryWrapper<OrderOvertime> wrapper1 = new QueryWrapper<>();
                wrapper1.eq("order_info_id",orderInfo.getOrderInfoId());
                OrderOvertime one = orderOvertimeService.getOne(wrapper1);
                orderInfoDTO.setEndTime(one.getEndTime());
                orderInfoDTO.setEndoHour(one.getEndoHour());
                orderInfoDTO.setOrderPrice(one.getPayPrice());
                Integer payState = one.getPayState();
                for (OrderCode orderCode : values) {
                    if (payState==orderCode.getCode()){
                        stateName=orderCode.getMessage();
                        orderInfoDTO.setStateName(stateName);
                    }
                }
            }
            dto.add(orderInfoDTO);
        }
        PageInfo pageInfo = BeanUtil.toBean(page, PageInfo.class);
        pageInfo.setPages(page.getPages());
        pageInfo.setRecords(dto);
        return pageInfo;
    }

    @Override
    public PageInfo getUserOrdersByTime(GetUserOrderByTimeParam param) throws ParseException {
        QueryWrapper<OrderInfo> wrapper = new QueryWrapper<>();
        String startTime = param.getStartTime();
        String endTime = param.getEndTime();
        if (startTime!=null&&!"".equals(startTime)){
            wrapper.ge("start_time",startTime);
        }
        if (endTime!=null&&!"".equals(endTime)){
            String date = DateUtil.getTomorrowStringDate(endTime);
            wrapper.le("end_time",date);
        }
        Page<OrderInfo> page = new Page<>(param.getCurrent() == null ? 1 : param.getCurrent(), param.getSize() == null ? 3 : param.getSize());
        Page<OrderInfo> orderInfoPage = orderInfoMapper.selectPage(page, wrapper);
        List<OrderInfo> records = orderInfoPage.getRecords();
        ArrayList<OrderInfoDTO> dto=new ArrayList<OrderInfoDTO>();
        Integer userId = param.getUserId();
        Result<UserInfo> userInfoResult = userInfoClient.loadAllUserinfobyId(userId);
        UserInfo userInfo = userInfoResult.getData();
        for (OrderInfo orderInfo : records) {
            OrderInfoDTO orderInfoDTO = BeanUtil.toBean(orderInfo, OrderInfoDTO.class);
            orderInfoDTO.setUserInfoName(userInfo.getUserInfoName());
            Integer centifiedInfoId = orderInfo.getCentifiedInfoId();
            Result<CertifiedInfo> certifiedInfoResult = certifiedClient.findCertifiedInfoById(centifiedInfoId);
            CertifiedInfo certifiedInfo = certifiedInfoResult.getData();
            orderInfoDTO.setCertifiedInfoName(certifiedInfo.getCertifiedInfoName());
            Result<String> stallNum = stallInfoClient.findStallNumById(orderInfoDTO.getStatllInfoId());
            orderInfoDTO.setStallInfoNum(stallNum.getData());
            Integer state = orderInfo.getOrderInfoState();
            String stateName=null;
            OrderCode[] values = OrderCode.values();
            for (OrderCode orderCode : values) {
                if (state==orderCode.getCode()){
                    stateName=orderCode.getMessage();
                }
            }
            orderInfoDTO.setStateName(stateName);
            if (orderInfo.getIsOvertime()==OrderCode.ORDER_OVER_TIME.getCode()){
                QueryWrapper<OrderOvertime> wrapper1 = new QueryWrapper<>();
                wrapper1.eq("order_info_id",orderInfo.getOrderInfoId());
                OrderOvertime one = orderOvertimeService.getOne(wrapper1);
                orderInfoDTO.setEndTime(one.getEndTime());
                orderInfoDTO.setEndoHour(one.getEndoHour());
                orderInfoDTO.setOrderPrice(one.getPayPrice());
                Integer payState = one.getPayState();
                for (OrderCode orderCode : values) {
                    if (payState==orderCode.getCode()){
                        stateName=orderCode.getMessage();
                        orderInfoDTO.setStateName(stateName);
                    }
                }
            }
            dto.add(orderInfoDTO);
        }
        PageInfo pageInfo = BeanUtil.toBean(page, PageInfo.class);
        pageInfo.setPages(page.getPages());
        pageInfo.setRecords(dto);
        return pageInfo;
    }

    @Override
    public PageInfo getUserOrdersByState(GetUserOrderByStateParam param) {
        Integer userId = param.getUserId();
        Result<UserInfo> userInfoResult = userInfoClient.loadAllUserinfobyId(userId);
        UserInfo userInfo = userInfoResult.getData();
        Page<OrderInfo> page = new Page<>(param.getCurrent() == null ? 1 : param.getCurrent(), param.getSize() == null ? 3 : param.getSize());
        Integer stateId = param.getStateId();
        OrderCode[] values = OrderCode.values();
        boolean b=true;
        for (OrderCode orderCode : values) {
            if (stateId==orderCode.getCode()){
                b=false;
            }
        }
        if (b){
            throw new OrderException(OrderExceptionCode.ORDER_STATE_NOT_HAVE);
        }
        QueryWrapper<OrderInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("user_info_id",userId);
        wrapper.eq("order_info_state",stateId);
        Page<OrderInfo> orderInfoPage = orderInfoMapper.selectPage(page, wrapper);
        List<OrderInfo> records = orderInfoPage.getRecords();
        ArrayList<OrderInfoDTO> dto=new ArrayList<OrderInfoDTO>();
        for (OrderInfo orderInfo : records) {
            OrderInfoDTO orderInfoDTO = BeanUtil.toBean(orderInfo, OrderInfoDTO.class);
            orderInfoDTO.setUserInfoName(userInfo.getUserInfoName());
            Integer centifiedInfoId = orderInfo.getCentifiedInfoId();
            Result<CertifiedInfo> certifiedInfoResult = certifiedClient.findCertifiedInfoById(centifiedInfoId);
            CertifiedInfo certifiedInfo = certifiedInfoResult.getData();
            orderInfoDTO.setCertifiedInfoName(certifiedInfo.getCertifiedInfoName());
            Result<String> stallNum = stallInfoClient.findStallNumById(orderInfoDTO.getStatllInfoId());
            orderInfoDTO.setStallInfoNum(stallNum.getData());
            Integer state = orderInfo.getOrderInfoState();
            String stateName=null;
            for (OrderCode orderCode : values) {
                if (state==orderCode.getCode()){
                    stateName=orderCode.getMessage();
                }
            }
            orderInfoDTO.setStateName(stateName);
            if (orderInfo.getIsOvertime()==OrderCode.ORDER_OVER_TIME.getCode()){
                QueryWrapper<OrderOvertime> wrapper1 = new QueryWrapper<>();
                wrapper1.eq("order_info_id",orderInfo.getOrderInfoId());
                OrderOvertime one = orderOvertimeService.getOne(wrapper1);
                orderInfoDTO.setEndTime(one.getEndTime());
                orderInfoDTO.setEndoHour(one.getEndoHour());
                orderInfoDTO.setOrderPrice(one.getPayPrice());
                Integer payState = one.getPayState();
                for (OrderCode orderCode : values) {
                    if (payState==orderCode.getCode()){
                        stateName=orderCode.getMessage();
                        orderInfoDTO.setStateName(stateName);
                    }
                }
            }
            dto.add(orderInfoDTO);
        }
        PageInfo pageInfo = BeanUtil.toBean(page, PageInfo.class);
        pageInfo.setPages(page.getPages());
        pageInfo.setRecords(dto);
        return pageInfo;
    }

    @Override
    public List<OrderInfo> getOrderInfosByStallIds(Set<Integer> stallIds) {
        QueryWrapper<OrderInfo> wrapper = new QueryWrapper<>();
        wrapper.in("statll_info_id",stallIds);
        LocalTime now = LocalTime.now();
        wrapper.ge("end_time",now);
        List<OrderInfo> list = orderInfoMapper.selectList(wrapper);
        return list;
    }

    @Override
    public List<OrderInfo> getOrdersByStallIdAndTime(GetOrdersByStallIdAndTimeForm form) {
        Integer stallId = form.getStallId();
        String startTime = form.getStartTime();
        String endTime = form.getEndTime();
        QueryWrapper<OrderInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("statll_info_id",stallId);
        wrapper.between("start_time",startTime,endTime).or();
        wrapper.between("end_time",startTime,endTime).or();
        wrapper.le("start_time",startTime).ge("end_time",endTime);
        List<OrderInfo> list = orderInfoMapper.selectList(wrapper);
        return list;
    }

    @Override
    public void setHadComment(OrderInfo orderInfo) {
        UpdateWrapper<OrderInfo> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("order_info_id",orderInfo.getOrderInfoId());
        updateWrapper.set("is_comment",orderInfo.getIsComment());
        orderInfoMapper.update(null,updateWrapper);
    }

    @Override
    public List<OrderInfoDTO> getNoCommentOrder(Integer id) {
        Result<UserInfo> userInfoResult = userInfoClient.loadAllUserinfobyId(id);
        UserInfo userInfo = userInfoResult.getData();
        QueryWrapper<OrderInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("user_info_id",id);
        wrapper.eq("is_comment",OrderCode.ORDER_NO_COMMENT.getCode());
        List<OrderInfo> orderInfos = orderInfoMapper.selectList(wrapper);
        ArrayList<OrderInfoDTO> dto=new ArrayList<OrderInfoDTO>();
        OrderCode[] values = OrderCode.values();
        for (OrderInfo orderInfo : orderInfos) {
            OrderInfoDTO orderInfoDTO = BeanUtil.toBean(orderInfo, OrderInfoDTO.class);
            orderInfoDTO.setUserInfoName(userInfo.getUserInfoName());
            Integer centifiedInfoId = orderInfo.getCentifiedInfoId();
            Result<CertifiedInfo> certifiedInfoResult = certifiedClient.findCertifiedInfoById(centifiedInfoId);
            CertifiedInfo certifiedInfo = certifiedInfoResult.getData();
            orderInfoDTO.setCertifiedInfoName(certifiedInfo.getCertifiedInfoName());
            Result<String> stallNum = stallInfoClient.findStallNumById(orderInfoDTO.getStatllInfoId());
            orderInfoDTO.setStallInfoNum(stallNum.getData());
            Integer state = orderInfo.getOrderInfoState();
            String stateName=null;
            for (OrderCode orderCode : values) {
                if (state==orderCode.getCode()){
                    stateName=orderCode.getMessage();
                }
            }
            orderInfoDTO.setStateName(stateName);
            if (orderInfo.getIsOvertime()==OrderCode.ORDER_OVER_TIME.getCode()){
                QueryWrapper<OrderOvertime> wrapper1 = new QueryWrapper<>();
                wrapper1.eq("order_info_id",orderInfo.getOrderInfoId());
                OrderOvertime one = orderOvertimeService.getOne(wrapper1);
                orderInfoDTO.setEndTime(one.getEndTime());
                orderInfoDTO.setEndoHour(one.getEndoHour());
                orderInfoDTO.setOrderPrice(one.getPayPrice());
                Integer payState = one.getPayState();
                for (OrderCode orderCode : values) {
                    if (payState==orderCode.getCode()){
                        stateName=orderCode.getMessage();
                        orderInfoDTO.setStateName(stateName);
                    }
                }
            }
            dto.add(orderInfoDTO);
        }
        return dto;
    }

    @Override
    public String getTodayIncomeByCerId(Integer certifiedInfoId) throws ParseException {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        LocalDate today = LocalDate.now();
        // 获取今天的开始时间和结束时间
        Date parseStart = dateFormat.parse(today + " 00:00:00");
        Date parseEnd = dateFormat.parse(today + " 23:59:59");
        String todayStartString = dateFormat.format(parseStart);
        String todayEndString = dateFormat.format(parseEnd);
        QueryWrapper<OrderInfo> wrapper = new QueryWrapper<>();
        wrapper.between("start_time",todayStartString,todayEndString);
        wrapper.eq("centified_info_id",certifiedInfoId)
                .and(w->w.eq("order_info_state",OrderCode.ORDER_HAS_PAY_Earnest.getCode())
                        .or().eq("order_info_state",OrderCode.ORDER_PAYED.getCode())
                        .or().eq("order_info_state",OrderCode.ORDER_OVER_TIME_NOT_PAY.getCode())
                        .or().eq("order_info_state",OrderCode.ORDER_OVER_TIME_PAYED.getCode()));
        List<OrderInfo> orderInfos = orderInfoMapper.selectList(wrapper);
        System.out.println("==============");
        System.out.println(orderInfos.size());
        Double income= (double) 0;
        for (OrderInfo orderInfo : orderInfos) {
            Integer statllInfoId = orderInfo.getStatllInfoId();
            Result<StallInfo> stallInfoResult = stallInfoClient.findStallById(statllInfoId);
            StallInfo stallInfo = stallInfoResult.getData();

            //如果是业主的车位，开始分成
            if (stallInfo.getStallInfoAffiliation()== StallInfoCode.STALL_OF_RENTER.getCode()){
                //如果是超时订单
                if (orderInfo.getIsOvertime()==OrderCode.ORDER_OVER_TIME.getCode()){
                    //先加上已经支付的定金
                    double v = orderInfo.getOrderPrice().divide(new BigDecimal(2)).doubleValue();
                    v=v*0.2;
                    income=income+v;
                    //找到超时订单的价格
                    OrderOvertime orderOvertime=orderOvertimeService.getByOrderInfoId(orderInfo.getOrderInfoId());
                    //如果超时订单已经支付
                    if (orderOvertime.getPayState()==OrderCode.ORDER_OVER_TIME_PAYED.getCode()){
                        double v1 = orderOvertime.getPayPrice().doubleValue();
                        v1=v1*0.2;
                        income=income+v1;
                    }
                }else {
                    //不是超时订单
                    if (orderInfo.getOrderInfoState()==OrderCode.ORDER_HAS_PAY_Earnest.getCode()){
                        //已支付定金状态
                        double v = orderInfo.getOrderPrice().divide(new BigDecimal(2)).doubleValue();
                        v=v*0.2;
                        income=income+v;
                    }
                    if (orderInfo.getOrderInfoState()==OrderCode.ORDER_PAYED.getCode()){
                        //已经支付状态
                        double v = orderInfo.getOrderPrice().doubleValue();
                        v=v*0.2;
                        income=income+v;
                    }
                }
            }else {
                //如果是物业自己的车位
                //如果是超时订单
                if (orderInfo.getIsOvertime()==OrderCode.ORDER_OVER_TIME.getCode()){
                    //先加上已经支付的定金
                    double v = orderInfo.getOrderPrice().divide(new BigDecimal(2)).doubleValue();
                    v=v*0.9;
                    income=income+v;
                    //找到超时订单的价格
                    OrderOvertime orderOvertime=orderOvertimeService.getByOrderInfoId(orderInfo.getOrderInfoId());
                    //如果超时订单已经支付
                    if (orderOvertime.getPayState()==OrderCode.ORDER_OVER_TIME_PAYED.getCode()){
                        double v1 = orderOvertime.getPayPrice().doubleValue();
                        v1=v1*0.9;
                        income=income+v1;
                    }
                }else {
                    //不是超时订单
                    if (orderInfo.getOrderInfoState()==OrderCode.ORDER_HAS_PAY_Earnest.getCode()){
                        //已支付定金状态
                        double v = orderInfo.getOrderPrice().divide(new BigDecimal(2)).doubleValue();
                        v=v*0.9;
                        income=income+v;
                    }
                    if (orderInfo.getOrderInfoState()==OrderCode.ORDER_PAYED.getCode()){
                        //已经支付状态
                        double v = orderInfo.getOrderPrice().doubleValue();
                        v=v*0.9;
                        income=income+v;
                    }
                }
            }

        }
        return df.format(income);
    }

    @Override
    public String platGetTodayIncome() throws ParseException {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        LocalDate today = LocalDate.now();
        // 获取今天的开始时间和结束时间
        Date parseStart = dateFormat.parse(today + " 00:00:00");
        Date parseEnd = dateFormat.parse(today + " 23:59:59");
        String todayStartString = dateFormat.format(parseStart);
        String todayEndString = dateFormat.format(parseEnd);
        QueryWrapper<OrderInfo> wrapper = new QueryWrapper<>();
        wrapper.between("start_time",todayStartString,todayEndString);
        wrapper.eq("order_info_state",OrderCode.ORDER_HAS_PAY_Earnest.getCode())
                .or().eq("order_info_state",OrderCode.ORDER_PAYED.getCode())
                .or().eq("order_info_state",OrderCode.ORDER_OVER_TIME_NOT_PAY.getCode())
                .or().eq("order_info_state",OrderCode.ORDER_OVER_TIME_PAYED.getCode());
        List<OrderInfo> orderInfos = orderInfoMapper.selectList(wrapper);
        Double income= (double) 0;
        for (OrderInfo orderInfo : orderInfos) {
            //如果是超时订单
            if (orderInfo.getIsOvertime()==OrderCode.ORDER_OVER_TIME.getCode()){
                //先加上已经支付的定金
                double v = orderInfo.getOrderPrice().divide(new BigDecimal(2)).doubleValue();
                income=income+v;
                //找到超时订单的价格
                OrderOvertime orderOvertime=orderOvertimeService.getByOrderInfoId(orderInfo.getOrderInfoId());
                //如果超时订单已经支付
                if (orderOvertime.getPayState()==OrderCode.ORDER_OVER_TIME_PAYED.getCode()){
                    double v1 = orderOvertime.getPayPrice().doubleValue();
                    income=income+v1;
                }
            }else {
                //不是超时订单
                if (orderInfo.getOrderInfoState()==OrderCode.ORDER_HAS_PAY_Earnest.getCode()){
                    //已支付定金状态
                    BigDecimal halfOrderPrice = orderInfo.getOrderPrice().divide(new BigDecimal(2), 2, RoundingMode.HALF_UP);
                    double value = halfOrderPrice.doubleValue();
                    income=income+value;
                }
                if (orderInfo.getOrderInfoState()==OrderCode.ORDER_PAYED.getCode()){
                    //已经支付状态
                    double v = orderInfo.getOrderPrice().doubleValue();
                    income=income+v;
                }
            }
        }
        income=income*0.1;
        return df.format(income);
    }

    @Override
    public String renterGetTodayInCome(Integer renterId) throws ParseException {
        Result<RentersInfo> rentersInfoResult = rentersClient.loadAllRentersinfobyId(renterId);
        RentersInfo rentersInfo = rentersInfoResult.getData();
        String stallInfoIdString = rentersInfo.getStallInfoId();
        JSONArray jsonArray = JSONUtil.parseArray(stallInfoIdString);
        List<Integer> stallInfoIds = jsonArray.toList(Integer.class);
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        LocalDate today = LocalDate.now();
        // 获取今天的开始时间和结束时间
        Date parseStart = dateFormat.parse(today + " 00:00:00");
        Date parseEnd = dateFormat.parse(today + " 23:59:59");
        String todayStartString = dateFormat.format(parseStart);
        String todayEndString = dateFormat.format(parseEnd);
        QueryWrapper<OrderInfo> wrapper = new QueryWrapper<>();
        wrapper.in("statll_info_id",stallInfoIds);
        wrapper.between("start_time",todayStartString,todayEndString);
        wrapper.eq("order_info_state",OrderCode.ORDER_HAS_PAY_Earnest.getCode())
                .or().eq("order_info_state",OrderCode.ORDER_PAYED.getCode())
                .or().eq("order_info_state",OrderCode.ORDER_OVER_TIME_NOT_PAY.getCode())
                .or().eq("order_info_state",OrderCode.ORDER_OVER_TIME_PAYED.getCode());
        List<OrderInfo> orderInfos = orderInfoMapper.selectList(wrapper);
        Double income= (double) 0;
        for (OrderInfo orderInfo : orderInfos) {
            //如果是超时订单
            if (orderInfo.getIsOvertime()==OrderCode.ORDER_OVER_TIME.getCode()){
                //先加上已经支付的定金
                double v = orderInfo.getOrderPrice().divide(new BigDecimal(2)).doubleValue();
                income=income+v;
                //找到超时订单的价格
                OrderOvertime orderOvertime=orderOvertimeService.getByOrderInfoId(orderInfo.getOrderInfoId());
                //如果超时订单已经支付
                if (orderOvertime.getPayState()==OrderCode.ORDER_OVER_TIME_PAYED.getCode()){
                    double v1 = orderOvertime.getPayPrice().doubleValue();
                    income=income+v1;
                }
            }else {
                //不是超时订单
                if (orderInfo.getOrderInfoState()==OrderCode.ORDER_HAS_PAY_Earnest.getCode()){
                    //已支付定金状态
                    BigDecimal halfOrderPrice = orderInfo.getOrderPrice().divide(new BigDecimal(2), 2, RoundingMode.HALF_UP);
                    double value = halfOrderPrice.doubleValue();
                    income=income+value;
                }
                if (orderInfo.getOrderInfoState()==OrderCode.ORDER_PAYED.getCode()){
                    //已经支付状态
                    double v = orderInfo.getOrderPrice().doubleValue();
                    income=income+v;
                }
            }
        }
        income=income*0.7;
        return df.format(income);
    }

    @Override
    public String cerGetMonthInCome(Integer certifiedInfoId) throws ParseException {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        LocalDate now = LocalDate.now();
        LocalDate firstDay = now.with(TemporalAdjusters.firstDayOfMonth());
        LocalDate lastDay = now.with(TemporalAdjusters.lastDayOfMonth());
        Date parseStart = dateFormat.parse(firstDay + " 00:00:00");
        Date parseEnd = dateFormat.parse(lastDay + " 23:59:59");
        String StartString = dateFormat.format(parseStart);
        String EndString = dateFormat.format(parseEnd);
        QueryWrapper<OrderInfo> wrapper = new QueryWrapper<>();
        wrapper.between("start_time",StartString,EndString);
        wrapper.eq("centified_info_id",certifiedInfoId)
                .and(w->w.eq("order_info_state",OrderCode.ORDER_HAS_PAY_Earnest.getCode())
                        .or().eq("order_info_state",OrderCode.ORDER_PAYED.getCode())
                        .or().eq("order_info_state",OrderCode.ORDER_OVER_TIME_NOT_PAY.getCode())
                        .or().eq("order_info_state",OrderCode.ORDER_OVER_TIME_PAYED.getCode()));
        List<OrderInfo> orderInfos = orderInfoMapper.selectList(wrapper);
        System.out.println("==============");
        System.out.println(orderInfos.size());
        Double income= (double) 0;
        for (OrderInfo orderInfo : orderInfos) {
            Integer statllInfoId = orderInfo.getStatllInfoId();
            Result<StallInfo> stallInfoResult = stallInfoClient.findStallById(statllInfoId);
            StallInfo stallInfo = stallInfoResult.getData();

            //如果是业主的车位，开始分成
            if (stallInfo.getStallInfoAffiliation()== StallInfoCode.STALL_OF_RENTER.getCode()){
                //如果是超时订单
                if (orderInfo.getIsOvertime()==OrderCode.ORDER_OVER_TIME.getCode()){
                    //先加上已经支付的定金
                    double v = orderInfo.getOrderPrice().divide(new BigDecimal(2)).doubleValue();
                    v=v*0.2;
                    income=income+v;
                    //找到超时订单的价格
                    OrderOvertime orderOvertime=orderOvertimeService.getByOrderInfoId(orderInfo.getOrderInfoId());
                    //如果超时订单已经支付
                    if (orderOvertime.getPayState()==OrderCode.ORDER_OVER_TIME_PAYED.getCode()){
                        double v1 = orderOvertime.getPayPrice().doubleValue();
                        v1=v1*0.2;
                        income=income+v1;
                    }
                }else {
                    //不是超时订单
                    if (orderInfo.getOrderInfoState()==OrderCode.ORDER_HAS_PAY_Earnest.getCode()){
                        //已支付定金状态
                        double v = orderInfo.getOrderPrice().divide(new BigDecimal(2)).doubleValue();
                        v=v*0.2;
                        income=income+v;
                    }
                    if (orderInfo.getOrderInfoState()==OrderCode.ORDER_PAYED.getCode()){
                        //已经支付状态
                        double v = orderInfo.getOrderPrice().doubleValue();
                        v=v*0.2;
                        income=income+v;
                    }
                }
            }else {
                //如果是物业自己的车位
                //如果是超时订单
                if (orderInfo.getIsOvertime()==OrderCode.ORDER_OVER_TIME.getCode()){
                    //先加上已经支付的定金
                    double v = orderInfo.getOrderPrice().divide(new BigDecimal(2)).doubleValue();
                    v=v*0.9;
                    income=income+v;
                    //找到超时订单的价格
                    OrderOvertime orderOvertime=orderOvertimeService.getByOrderInfoId(orderInfo.getOrderInfoId());
                    //如果超时订单已经支付
                    if (orderOvertime.getPayState()==OrderCode.ORDER_OVER_TIME_PAYED.getCode()){
                        double v1 = orderOvertime.getPayPrice().doubleValue();
                        v1=v1*0.9;
                        income=income+v1;
                    }
                }else {
                    //不是超时订单
                    if (orderInfo.getOrderInfoState()==OrderCode.ORDER_HAS_PAY_Earnest.getCode()){
                        //已支付定金状态
                        double v = orderInfo.getOrderPrice().divide(new BigDecimal(2)).doubleValue();
                        v=v*0.9;
                        income=income+v;
                    }
                    if (orderInfo.getOrderInfoState()==OrderCode.ORDER_PAYED.getCode()){
                        //已经支付状态
                        double v = orderInfo.getOrderPrice().doubleValue();
                        v=v*0.9;
                        income=income+v;
                    }
                }
            }

        }
        return df.format(income);
    }

    @Override
    public String platGetMonthInCome() throws ParseException {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        LocalDate now = LocalDate.now();
        LocalDate firstDay = now.with(TemporalAdjusters.firstDayOfMonth());
        LocalDate lastDay = now.with(TemporalAdjusters.lastDayOfMonth());
        Date parseStart = dateFormat.parse(firstDay + " 00:00:00");
        Date parseEnd = dateFormat.parse(lastDay + " 23:59:59");
        String StartString = dateFormat.format(parseStart);
        String EndString = dateFormat.format(parseEnd);
        QueryWrapper<OrderInfo> wrapper = new QueryWrapper<>();
        wrapper.between("start_time",StartString,EndString);
        wrapper.eq("order_info_state",OrderCode.ORDER_HAS_PAY_Earnest.getCode())
                        .or().eq("order_info_state",OrderCode.ORDER_PAYED.getCode())
                        .or().eq("order_info_state",OrderCode.ORDER_OVER_TIME_NOT_PAY.getCode())
                        .or().eq("order_info_state",OrderCode.ORDER_OVER_TIME_PAYED.getCode());
        List<OrderInfo> orderInfos = orderInfoMapper.selectList(wrapper);
        Double income= (double) 0;
        for (OrderInfo orderInfo : orderInfos) {
            //如果是超时订单
            if (orderInfo.getIsOvertime()==OrderCode.ORDER_OVER_TIME.getCode()){
                //先加上已经支付的定金
                double v = orderInfo.getOrderPrice().divide(new BigDecimal(2)).doubleValue();
                income=income+v;
                //找到超时订单的价格
                OrderOvertime orderOvertime=orderOvertimeService.getByOrderInfoId(orderInfo.getOrderInfoId());
                //如果超时订单已经支付
                if (orderOvertime.getPayState()==OrderCode.ORDER_OVER_TIME_PAYED.getCode()){
                    double v1 = orderOvertime.getPayPrice().doubleValue();
                    income=income+v1;
                }
            }else {
                //不是超时订单
                if (orderInfo.getOrderInfoState()==OrderCode.ORDER_HAS_PAY_Earnest.getCode()){
                    //已支付定金状态
                    BigDecimal halfOrderPrice = orderInfo.getOrderPrice().divide(new BigDecimal(2), 2, RoundingMode.HALF_UP);
                    double value = halfOrderPrice.doubleValue();
                    income=income+value;
                }
                if (orderInfo.getOrderInfoState()==OrderCode.ORDER_PAYED.getCode()){
                    //已经支付状态
                    double v = orderInfo.getOrderPrice().doubleValue();
                    income=income+v;
                }
            }
        }
        income=income*0.1;
        return df.format(income);
    }

    @Override
    public String renterGetMonthInCome(Integer renterId) throws ParseException {
        Result<RentersInfo> rentersInfoResult = rentersClient.loadAllRentersinfobyId(renterId);
        RentersInfo rentersInfo = rentersInfoResult.getData();
        String stallInfoIdString = rentersInfo.getStallInfoId();
        JSONArray jsonArray = JSONUtil.parseArray(stallInfoIdString);
        List<Integer> stallInfoIds = jsonArray.toList(Integer.class);
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        LocalDate now = LocalDate.now();
        LocalDate firstDay = now.with(TemporalAdjusters.firstDayOfMonth());
        LocalDate lastDay = now.with(TemporalAdjusters.lastDayOfMonth());
        Date parseStart = dateFormat.parse(firstDay + " 00:00:00");
        Date parseEnd = dateFormat.parse(lastDay + " 23:59:59");
        String StartString = dateFormat.format(parseStart);
        String EndString = dateFormat.format(parseEnd);
        QueryWrapper<OrderInfo> wrapper = new QueryWrapper<>();
        wrapper.in("statll_info_id",stallInfoIds);
        wrapper.between("start_time",StartString,EndString);
        wrapper.eq("order_info_state",OrderCode.ORDER_HAS_PAY_Earnest.getCode())
                .or().eq("order_info_state",OrderCode.ORDER_PAYED.getCode())
                .or().eq("order_info_state",OrderCode.ORDER_OVER_TIME_NOT_PAY.getCode())
                .or().eq("order_info_state",OrderCode.ORDER_OVER_TIME_PAYED.getCode());
        List<OrderInfo> orderInfos = orderInfoMapper.selectList(wrapper);
        Double income= (double) 0;
        for (OrderInfo orderInfo : orderInfos) {
            //如果是超时订单
            if (orderInfo.getIsOvertime()==OrderCode.ORDER_OVER_TIME.getCode()){
                //先加上已经支付的定金
                double v = orderInfo.getOrderPrice().divide(new BigDecimal(2)).doubleValue();
                income=income+v;
                //找到超时订单的价格
                OrderOvertime orderOvertime=orderOvertimeService.getByOrderInfoId(orderInfo.getOrderInfoId());
                //如果超时订单已经支付
                if (orderOvertime.getPayState()==OrderCode.ORDER_OVER_TIME_PAYED.getCode()){
                    double v1 = orderOvertime.getPayPrice().doubleValue();
                    income=income+v1;
                }
            }else {
                //不是超时订单
                if (orderInfo.getOrderInfoState()==OrderCode.ORDER_HAS_PAY_Earnest.getCode()){
                    //已支付定金状态
                    BigDecimal halfOrderPrice = orderInfo.getOrderPrice().divide(new BigDecimal(2), 2, RoundingMode.HALF_UP);
                    double value = halfOrderPrice.doubleValue();
                    income=income+value;
                }
                if (orderInfo.getOrderInfoState()==OrderCode.ORDER_PAYED.getCode()){
                    //已经支付状态
                    double v = orderInfo.getOrderPrice().doubleValue();
                    income=income+v;
                }
            }
        }
        income=income*0.7;
        return df.format(income);
    }


}
